<template>
  <div class="material_map_box">
    <div class="inner_content_box">
      <div class="single_1_box_common">
        <div class="com_title_c"><img class="com_title_img" src="../../assets/img/openlayer/1.png">Cesium材质</div>
        <div class="un_coding_c">（1）cesium有许多的内置材质，最常用的就是Color和Image等。</div>
        <div class="un_coding_c">（2）材质的创建有两种方式，快捷方式和原始方式。</div>
        <div class="coding_1_box_common coding_row_1" style="height: 700px;">
          <pre><code class="language-javascript"
                     v-text="content"></code></pre>
        </div>
        <div class="un_coding_c">（3）GLSL定义材质。</div>
        <div class="coding_1_box_common coding_row_1" style="height: 700px;">
          <pre><code class="language-javascript"
                     v-text="content1"></code></pre>
        </div>
      </div>
      <div class="single_1_box_common">
        <div class="com_title_c"><img class="com_title_img" src="../../assets/img/openlayer/1.png">展示</div>
        <div class="map_content_box"  id="map_content_7"></div>
        <div class="coding_1_box_common coding_row_1">
          <pre><code class="language-javascript"
                     v-text="content2"></code></pre>
        </div>
      </div>

    </div>

  </div>
</template>

<script lang="ts" setup>
import Prism from 'prismjs';
import {nextTick, onMounted, ref} from "vue";
import { initMap,createPrimitives } from "./js/initMap";
const cviewer:any=ref(undefined)
const content = `
//设置图片快捷方式和原始方式
polygon.material=Material.fromType('Image');
polygon.material.uniforms.image = 'image.png';

polygon.material = new Cesium.Material({
  fabric : {
    type : 'Image',
    uniforms : {
      image : 'image.png',
      image : '图片内容base64编码'
    }
  }
});

//设置颜色快捷方式和原始方式
polygon.material = new Cesium.Material({
  fabric : {
    type : 'Color',
    uniforms : {
      color : new Cesium.Color(1.0, 0.0, 0.0, 0.5)
    }
  }
});

polygon.material.uniforms.color = Cesium.Color.WHITE;

//Fabric的JSON结构描述在Cesium仓库中。所有Fabric属性、子属性的细节，包括type, materials, uniforms, components, source。
//uniforms是一个webgl的概念，用于与顶点无关的数据
`
const content1=`
//最灵活的一种定义材质的方式，为Fabric指定source属性，在cesium源码中会读取source并加工合并到最终的着色器中进行图形绘制。
struct czm_materialInput
{
  float s;
  vec2 st;
  vec3 str;
  mat3 tangentToEyeMatrix;
  vec3 positionToEyeEC;
  vec3 normalEC;
};

struct czm_material
{
  vec3 diffuse;
  float specular;
  float shininess;
  vec3 normal;
  vec3 emission;
  float alpha;
};

czm_material czm_getMaterial(czm_materialInput materialInput);
{
  source : 'czm_material czm_getMaterial(czm_materialInput materialInput) { return czm_getDefaultMaterial(materialInput); }'
}

//这也是我们写shader的切入点

`
const content2=`
import {
    Viewer,
    Ellipsoid,
    GeographicProjection,
    ImageryLayer,
    Ion,
    Color as CesiumColor,
    PostProcessStageLibrary ,
    ArcGisMapServerImageryProvider,
    SingleTileImageryProvider,
    Primitive,
    GeometryInstance,
    RectangleGeometry,
    Rectangle,
    EllipsoidSurfaceAppearance,
    Math as  CesiumMath,
    Cartesian3,
    Material
} from  'cesium'

 export  const  initMap=(id:string,extent:Array<number>)=>{
    let cgs2000Ellipsolid = new Ellipsoid(6378137.0, 6378137.0, 6356752.31414035585)
    var cgs2000GeographicProj = new GeographicProjection(cgs2000Ellipsolid)
    Ion.defaultAccessToken =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI1ODRiY2NiYi1jMmVlLTRkNTctYTNhNy03ZGNlMGQ2YmNjZTQiLCJpZCI6MTQwMDIsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1NjQ1NTU1MDV9.6E9-n__jfDwX1e-C3H685NhJZ8HUx3BQ7FYEJ9Rz9Ec'
    let viewer:any = new Viewer(id, {
      infoBox: false,
      geocoder: false,
      mapProjection: cgs2000GeographicProj,
      fullscreenButton: false,
      homeButton: false, //是否显示Home按钮
      sceneModePicker: false, //是否显示3D/2D选择器
      // baseLayerPicker: false,//是否显示图层选择器
      navigationHelpButton: false, //是否显示右上角的帮助按钮
      navigationInstructionsInitiallyVisible: false,
      animation: true, //是否创建动画小器件，左下角仪表
      timeline: true, //是否显示时间轴
      vrButton: false,
      selectionIndicator: false, //是否显示选取指示器组件
      requestRenderMode: true,  //开启显示渲染
      maximumRenderTimeChange:Infinity, //开启显示渲染
      showRenderLoopErrors: true, //是否显示渲染错误
      //baseLayerPicker和imageryProvider同时存在避免api.cesium.com
      baseLayerPicker: false,
      //解决图片打印问题
      contextOptions: {
        webgl: {
          alpha: true,
          depth: true,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          //通过canvas.toDataURL()实现截图需要将该项设置为true
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: true
        }
      },
        baseLayer: new ImageryLayer(new SingleTileImageryProvider({
            url: '',
            tileWidth:255,
            tileHeight:255
        })) ,
        // baseLayer:ImageryLayer.fromProviderAsync(
        //      ArcGisMapServerImageryProvider.fromUrl(
        //         "https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer", {token: "<ArcGIS Access Token>"})
        //     //     ArcGisMapServerImageryProvider.fromBasemapType(ArcGisBaseMapType.SATELLITE)
        // ),
    })
    viewer.scene.requestRender();
    // let _this = this
    // viewer._cesiumWidget._creditContainer.style.display = 'none' //隐藏版权信息
    //是否开启抗锯齿
    viewer.scene.postProcessStages.fxaa.enabled = false
    viewer.scene.screenSpaceCameraController.enableCollisionDetection = false
   const baseColor=CesiumColor.fromCssColorString('#000');
    viewer.scene.globe.baseColor = baseColor;
    // viewer.scene.globe.depthTestAgainstTerrain = true;
    var stages = viewer.scene.postProcessStages;
    viewer.scene.brightness = viewer.scene.brightness || stages.add(PostProcessStageLibrary.createBrightnessStage());
    viewer.scene.brightness.enabled = true;
    viewer.scene.brightness.uniforms.brightness = Number(1.23);
    // 时间轴的timeline:true 和  animation:true,因为轨迹需要，使用下面方式隐藏组件
    const timeLineContain:HTMLElement = <HTMLElement>document.querySelector(".cesium-viewer-timelineContainer");
    if(timeLineContain){
        timeLineContain.style.display = 'none';
    }
    const animateContain:HTMLElement= <HTMLElement> document.querySelector(".cesium-viewer-animationContainer");
    if(animateContain!==null){
        animateContain.style.display = 'none';
    }
     return viewer;
 }


/**
 * uniform还可以传入时间，生成动态效果
 * @param viewer
 */
export const  createPrimitives=(viewer:any)=> {
   const primitive= viewer.scene.primitives.add(
        new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: new RectangleGeometry({
                    rectangle: Rectangle.fromDegrees(116, 39, 117, 39.7),
                    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            }),
            appearance: new EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        })
    )
    viewer.camera.flyTo({
        destination : Cartesian3.fromDegrees(116.5, 39.35, 180000.0),
        orientation : {
            heading : CesiumMath.toRadians(0),
            pitch : CesiumMath.toRadians(-90.0),
            roll : 0.0
        }
    });
    //图片纹理
    const primitive1= viewer.scene.primitives.add(
        new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: new RectangleGeometry({
                    rectangle: Rectangle.fromDegrees(118, 39, 119, 39.7),
                    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            }),
            appearance: new EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        })
    )
    primitive1.appearance.material=new Material({
        fabric:{
            uniforms:{
                image:'/fj.jpeg' ,
                alpha:1.0
            },
            source:\`
            czm_material czm_getMaterial(czm_materialInput materialInput){
                            czm_material material=czm_getDefaultMaterial(materialInput);
                            material.diffuse=texture(image,materialInput.st).rgb;
                            return material;
                        }
            \`
        }
    })
    //挖孔
    const primitive2= viewer.scene.primitives.add(
        new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: new RectangleGeometry({
                    rectangle: Rectangle.fromDegrees(116, 38, 117, 38.7),
                    vertexFormat: EllipsoidSurfaceAppearance.VERTEX_FORMAT,
                })
            }),
            appearance: new EllipsoidSurfaceAppearance({
                aboveGround: false
            })
        })
    )
    primitive2.appearance.material=new Material({
        fabric:{
            uniforms:{
                image:'/fj.jpeg' ,
                alpha:1.0
            },
            source: \`
              czm_material czm_getMaterial(czm_materialInput materialInput){
                            czm_material material=czm_getDefaultMaterial(materialInput);
                            material.diffuse=texture(image,materialInput.st).rgb;
                            material.alpha=alpha;
                            vec2 center=vec2(0.5,0.5);
                            float dis=distance(center,materialInput.st);
                            if(dis>0.25){
                                material.diffuse=vec3(1.0,0.0,0.0);
                            }
                            if(dis<0.1){
                                material.diffuse=vec3(1.0);
                            }
                            return material;
                        }
            \`
        }
    })

}
`




onMounted(() => {
  nextTick(() => {
    Prism.highlightAll();
    cviewer.value=  initMap("map_content_7", [0, 0, 0, 0]);
    createPrimitives(cviewer.value);
  })

})
</script>

<style lang="scss" scoped>
/* 引入Prism.js的CSS主题 */
@import 'prismjs/themes/prism-tomorrow.css';
@import './css/common.css';

.material_map_box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row-reverse;
  background-color: rgba(44, 62, 80, 0.5);

  .inner_content_box {
    width: calc(100% - 300px - 100px - 500px);
    height: calc(100% - 20px);
    margin-top: 10px;
    margin-right: 350px;
    overflow-x: hidden;
    overflow-y: auto;
    background-color: rgba(255, 255, 255, 0.8);

  }

}
</style>
